package TEST01;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

//DBUtils工具类
public class DruidUtils {
    //1.定义成员变量
    public static DataSource dataSource;
    //2.静态代码块
    static {
        try {
            //2.1创建属性集对象
            Properties p = new Properties();
            //2.2加载配置文件 Druid连接池不能够主动加载配置文件,需要指定文件
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("db.properties");
            //2.3Properties对象的load方法 从字节流中读取配置信息
            p.load(inputStream);
            //2.4通过工厂类获取连接对象
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    //3.获取连接方法
    public static Connection getConnection() throws SQLException {
        Connection connection = (Connection) dataSource.getConnection();
        return connection;
    }

    //4.释放资源
    public static void close(Connection con, Statement statement){
        if(con != null && statement != null){
            try {
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if(con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}

